
import pickle
import os
import numpy as np
from global_data_2 import *

result_filedir = f'../result/{exp_key}'
all_start_time = 1585713600
# all_start_time = 1586318400 + 59*15*60
all_last_time = 1586923200


def get_score_or_matrix_data(number=2):
    filepath = f'{result_filedir}/result_for_period2_{number}'
    f_list = sorted([f for f in os.listdir(filepath) if 'test_score' in f])
    score_list, timestamp_list = [], []
    for f in f_list:
        try:
            timestamp = int(f.split('-')[0])
            if (timestamp >= all_start_time) and (timestamp <= all_last_time):
                with open(os.path.join(filepath, f), 'rb') as fr:
                    ip_list, score, label = pickle.load(fr)
                    score_list.append(np.nansum(score, axis=1))
                    timestamp_list.append(timestamp)
        except:
            continue
    score_matrix = np.array(score_list)
    return score_matrix, timestamp_list, ip_list


def save_file(number=2):
    os.makedirs(f'{exp_key}/label_data', exist_ok=True)
    score_matrix, timestamp_list, ip_list = get_score_or_matrix_data(number)
    # score_matrix 96*14 - (omni_windows_size - 1)
    with open(os.path.join(project_path, 'label_result', f"{number-1}.pkl"), 'wb') as fw:
        # print(f"len(score_matrix):{len(score_matrix)}")
        label_index = np.where(-score_matrix > 200)[0]
        label = np.zeros_like(score_matrix)
        label[label_index] = 1
        label = label[7*96 - (omni_windows_size-1):]
        label = label.squeeze()
        print(f"label.shape:{label.shape} np.sum(label):{np.sum(label)} np.mean(score_matrix):{np.mean(score_matrix)}")
        pickle.dump(label, fw)


for _i in range(1, cluster_num+1):
    save_file(_i)

